<?php
/**
 * @author ykm 2016-04-05
 * @describe 店铺商品相关接口
 */

class erpapi_shop_request_product extends erpapi_shop_request_abstract {

    protected function getUpdateStockApi() {
        return SHOP_UPDATE_ITEMS_QUANTITY_LIST_RPC;
    }

    public function updateStock($stocks, $dorelease = false) {
        $rs = array('rsp'=>'fail','msg'=>'','data'=>'');
        if (!$stocks) {
            $rs['msg'] = 'no stocks';
            return $rs;
        }
        $shop_id = $this->__channelObj->channel['shop_id'];
        $skuIds = array_keys($stocks);
        sort($stocks);
        //保存库存同步管理日志
        $oApiLogToStock = kernel::single('ome_api_log_to_stock');
        $oApiLogToStock->save($stocks,$shop_id);
        //待更新库存BN
        $params = array(
            'list_quantity' => json_encode($stocks),
        );
        $stockApi = $this->getUpdateStockApi($stocks);
        $callback = array(
            'class' => get_class($this),
            'method' => 'updateStockCallback',
            'params' => array(
                'shop_id' => $shop_id,
                'request_params' => $params,
                'api_name' => $stockApi
            )
        );
        $title = '批量更新店铺('.$this->__channelObj->channel['name'].')的库存(共'.count($stocks).'个)';
        $primaryBn = $this->__channelObj->channel['shop_bn'] . 'UpdateStock';
        $return = $this->__caller->call($stockApi,$params,$callback,$title, 10, $primaryBn);
        if ($return !== false){
            if ($dorelease === true) {
                if ($skuIds && app::get('inventorydepth')->is_installed()) {
                    app::get('inventorydepth')->model('shop_adjustment')->update(array('release_status'=>'running'),array('id'=>$skuIds));
                }
            }
            app::get('ome')->model('shop')->update(array('last_store_sync_time'=>time()),array('shop_id'=>$shop_id));
        }
        $rs['rsp'] = 'success';
        return $rs;
    }

    public function updateStockCallback($ret, $callback_params) {
        $status          = $ret['rsp'];
        $res             = $ret['res'];
        $data            = json_decode($ret['data'], true);
        $request_params  = $callback_params['request_params'];
        $msg_id          = $ret['msg_id'];
        $apiName         = $callback_params['api_name'];

        // 店铺信息
        if ($callback_params['shop_id']) {
            $shopModel = app::get('ome')->model('shop');
            $shop = $shopModel->dump(array('shop_id'=>$callback_params['shop_id']),'business_type');
        }
        // LOG PARAMS
        $log_params = array($apiName,$request_params,array(get_class($this),'updateStockCallback',$callback_params));
        if ($status != 'succ' && $status != 'fail' ){
            $res = $status . ome_api_func::api_code2msg('re001', '', 'public');
        }

        //更新失败的bn会返回，然后下次retry时，只执行失败的bn更新库存
        $err_item_bn = $data['error_response'];
        if (!is_array($err_item_bn)){
            $err_item_bn = json_decode($data['error_response'],true);
        }
        $itemsnum = json_decode($log_params[1]['list_quantity'],true);
        $new_itemsnum = $true_itemsnum = array();
        foreach($itemsnum as $k=>$v){
            if(in_array($v['bn'],$err_item_bn) && !in_array($v['bn'],(array) $data['true_bn']) ){
                $new_itemsnum[] = $v;
            } else {
                $true_itemsnum[] = $v;
            }
        }

        //当返回失败且BN为空时不更新list_quantity
        if ($status == 'succ' || $new_itemsnum){
            $log_params[1]['list_quantity'] = json_encode($new_itemsnum);
        }else{
            $new_itemsnum = $itemsnum;
        }

        $log_detail = array(
            'msg_id' => $msg_id,
            'params' => serialize($log_params),
        );
        //更新库存同步管理的执行状态
        $oApiLogToStock = kernel::single('ome_api_log_to_stock');
        if ($new_itemsnum) {
            $oApiLogToStock->save_callback($new_itemsnum,'fail',$callback_params['shop_id'],$res,$log_detail);
        }
        if ($true_itemsnum) {
            $oApiLogToStock->save_callback($true_itemsnum,'success',$callback_params['shop_id'],$res,$log_detail);
        }
        return $this->callback($ret, $callback_params);
    }

    #实时下载店铺商品
    public function itemsAllGet($filter,$offset=0,$limit=100)
    {
        $timeout = 20;
        $param = array(
            'page_no'        => $offset,
            'page_size'      => $limit,
            'fields'         => 'iid,outer_id,bn,num,title,default_img_url,modified,detail_url,approve_status,skus,price,barcode ',
        );
        $param = array_merge((array)$param,(array)$filter);
        $title = "获取店铺(" . $this->__channelObj->channel['name'] .')商品';
        $result = $this->__caller->call(SHOP_GET_ITEMS_ALL_RPC,$param,array(),$title,$timeout);
        if ($result['res_ltype'] > 0) {
            for ($i=0;$i<3;$i++) {
                $result = $this->__caller->call(SHOP_GET_ITEMS_ALL_RPC,$param,array(),$title,$timeout);
                if ($result['res_ltype'] == 0) {
                    break;
                }
            }
        }
        if($result['data']) {
            $result['data'] = json_decode($result['data'], true);
        }
        return $result;
    }

    #根据$iids实时获取店铺商品
    public function itemsListGet($iids)
    {
        if(!$iids) return false;
        if(is_array($iids)) $iids = implode(',', $iids);
        $timeout = 10;
        $param = array(
            'iids' => $iids,
        );
        $title = "根据IIDS获取店铺(" . $this->__channelObj->channel['name'] .')商品';
        $result = $this->__caller->call(SHOP_GET_ITEMS_LIST_RPC,$param,array(),$title,$timeout);
        if ($result->res_ltype > 0) {
            for ($i=0;$i<3;$i++) {
                $result = $this->__caller->call(SHOP_GET_ITEMS_LIST_RPC,$param,array(),$title,$timeout);
                if ($result->res_ltype == 0) {
                    break;
                }
            }
        }
        if($result['data']) {
            $result['data'] = json_decode($result['data'], true);
        }
        return $result;
    }

    #淘分销商品下载
    public function fenxiaoProductsGet($filter,$offset=0,$limit=20)
    {
        $timeout = 20;
        $param = array(
            'page_no'        => $offset,
            'page_size'      => $limit,
        );
        $param = array_merge((array)$param,(array)$filter);
        $title = '获取店铺(' . $this->__channelObj->channel['name'] . ')商品';
        $result = $this->__caller->call(SHOP_GET_FENXIAO_PRODUCTS,$param,array(),$title,$timeout);
        if ($result['res_ltype'] > 0) {
            for ($i=0;$i<3;$i++) {
                $result = $this->__caller->call(SHOP_GET_FENXIAO_PRODUCTS,$param,array(),$title,$timeout);
                if ($result['res_ltype'] == 0) {
                    break;
                }
            }
        }
        if($result['data']) {
            $result['data'] = json_decode($result['data'], true);
        }
        return $result;
    }

    #淘分销商品更新
    public function fenxiaoProductUpdate($param) {
        $timeout = 20;
        if (!$param['pid']) {
            return false;
        }
        $title = "更新店铺(" . $this->__channelObj->channel['name'] .')商品'.$param['pid'].'上下架状态';
        $result = $this->__caller->call(SHOP_UPDATE_FENXIAO_PRODUCT,$param,array(),$title,$timeout, $param['pid']);
        return $result;
    }

    #根据IID获取单个商品
    public function item_get($iid) {
        $title = '单拉商品[' . $iid . ']';
        $params = array(
            'iid' => $iid,
        );
        for ($i=0; $i<3; $i++) {
            $result = $this->__caller->call(SHOP_ITEM_GET,$params,array(),$title, 20, $iid);
            if ($result['rsp'] == 'succ') break;
        }
        
        if ($result['rsp'] != 'succ' || !$result['data']) return array();

        if ($result['data']) $result['data'] = @json_decode($result['data'],true);

        return $result;
    }

    public function item_sku_get($sku) {
        $title = '单拉商品SKU[' . ($sku['sku_id'] ? $sku['sku_id'] : $sku['iid']) . ']';
        $params = array(
            'sku_id' => $sku['sku_id'],
            'iid' => $sku['iid'],
            'num_iid' => $sku['iid'],
        );
        if ($sku['seller_uname']) $params['seller_uname'] = $sku['seller_uname'];
        for ($i=0; $i<3; $i++) {
            $result = $this->__caller->call(SHOP_ITEM_SKU_GET,$params,array(),$title, 20, ($sku['sku_id'] ? $sku['sku_id'] : $sku['iid']));
            if ($result['rsp'] == 'succ') break;
        }
        if ($result['rsp'] != 'succ' || !$result['data']) return array();
        
        if ($result['data']) $result['data'] = @json_decode($result['data'],true);

        return $result;
    }

    # 单个更新上下架
    public function approveStatusUpdate($approve) {
        if(!$approve) return false;
        $title = '更新店铺('.$this->__channelObj->channel['name'].')的('.($approve['title']?$approve['title']:$approve['iid']).')商品上下架状态';
        $params['iid'] = $approve['iid'];
        $params['approve_status'] = $approve['approve_status'];
        if($approve['approve_status'] == 'onsale') $params['num'] = $approve['num'];
        if($approve['outer_id']) $params['outer_id'] = $approve['outer_id'];
        $operinfo = kernel::single('ome_func')->getDesktopUser();
        $params = array_merge((array) $params,(array) $operinfo);
        $result = $this->__caller->call(SHOP_UPDATE_ITEM_APPROVE_STATUS_RPC,$params,array(),$title, 10, $params['iid']);
        return $result;
    }

    #批量更新商品上下架
    public function approveStatusListUpdate($approve_status) {
        if(!$approve_status) return false;
        $approve_status_msg = '';
        switch ($approve_status[0]['approve_status']) {
            case 'onsale':
                $approve_status_msg = '上架';
                break;
            case 'instock':
                $approve_status_msg = '下架';
                break;
            case 'is_pre_delete':
                $approve_status_msg = '预删除';
                break;
        }
        $title = '批量'.$approve_status_msg.'店铺('.$this->__channelObj->channel['name'].')的商品(共'.count($approve_status).'个)';
        $params = array(
            'list_quantity' => json_encode($approve_status),
        );
        $callback = array(
            'class' => get_class($this),
            'method' => 'approveStatusUpdateCallback',
            'params' => array(
                'list_quantity' => $params['list_quantity']
            )
        );

        $rs = $this->__caller->call(SHOP_UPDATE_ITEM_APPROVE_STATUS_LIST_RPC,$params,$callback,$title,10,'batchUpdateApprove');
        return $rs;
    }

    #批量上下架回调方法
    public function approveStatusUpdateCallback($response, $callback_params) {
        $list_quantity = json_decode($callback_params['list_quantity'],true);
        $approve_status = $list_quantity[0]['approve_status'];
        $true_bn = $response['data']['true_bn'];
        # 更新状态
        if ($true_bn) {
            $itemFilter = array(
                'bn' => $true_bn,
                'shop_id' => $callback_params['shop_id'],
            );
            if (app::get('inventorydepth')->is_installed()) {
                app::get('inventorydepth')->model('shop_items')->update(array('approve_status'=>$approve_status),$itemFilter);
            }
        }
        return $response;
    }

    #获取商品
    public function items_custom_get($productCode) {
        if (!$productCode) return false;
        $title = '获取单个商品[' . $productCode . ']';
        $params = array(
            'iid' => $productCode,
            //'bn'=>$productCode,
        );
        for ($i=0;$i<3;$i++) {
            $result = $this->__caller->call(SHOP_GET_ITEMS_CUSTOM,$params,array(),$title, 20, $productCode);
            if ($result['rsp'] == 'succ') {
                break;
            }
        }
        if($result['data']) {
            $result['data'] = json_decode($result['data'], true);
        }
        return $result;
    }
}
